package com.np.rtmpdump5;

import android.util.Log;

import java.util.concurrent.LinkedBlockingQueue;

public class BitmapLive extends Thread {

    private String TAG = "rtmpdump5_BitmapLive";
    private String url;
    private LinkedBlockingQueue<RTMPPackage> queue = new LinkedBlockingQueue<>();
    private boolean isLiving;

    static {
        System.loadLibrary("native-lib");
    }

    public void startLive(String url) {
        this.url = url;
        start();
    }

    @Override
    public void run() {
        if (!connect(url)) {
            return;
        }

        BitmapEncoder bitmapEncoder = new BitmapEncoder(this);
        bitmapEncoder.startEncode2();

        isLiving = true;
        while (isLiving) {
            RTMPPackage rtmpPackage = null;
            try {
                rtmpPackage = queue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
                Log.i(TAG, e.getMessage());
            }
            if (rtmpPackage.getBuffer() != null && rtmpPackage.getBuffer().length != 0) {
                Log.i(TAG, "java sendData");
                sendData(rtmpPackage.getBuffer(), rtmpPackage.getBuffer().length, rtmpPackage.getTms(), 0);
            }
        }
    }

    public void addPackage(RTMPPackage rtmpPackage) {
        if (!isLiving) {
            return;
        }
        queue.add(rtmpPackage);
    }

    /**
     * 断开连接，停止推流
     */
    public void close() {

    }

    private native boolean connect(String url);

    private native boolean sendData(byte[] data, int len, long tms, int type);
}
